var web = web || {};
web.ScrollLoading = Class.create(); 
web.ScrollLoading.prototype = {
	initialize: function(options) {
		var _this = this;
		this.settings = $.extend({
			real: 'data-url'
		}, options);
		
		this.cache = [];
		this.win = $(window);
		this.winHeight = this.win.height();
		
		this.win.bind({
			resize: function(){_this.winHeight = _this.win.height(); _this._showImgs();},
			scroll: function(){_this._showImgs();}
		});
	},
	addImgsAndShow: function(elems) {
		var _this = this;
		
		elems.each(function() {
			var img = $(this);
			var node = this.nodeName.toLowerCase(), url = img.attr(_this.settings.real);
			if (!url) return;
			
			_this.cache.push({obj: img, tag: node, url: url});
		});
		
		this._showImgs();
	},
	_showImgs: function() {
		var ts = this.win.scrollTop(), tn = ts + this.winHeight, its, itn;
		
		$.each(this.cache, function(i, data) {
			if (!data.obj || (data.tag != 'img')) return;
			
			its = data.obj.position().top;
			itn = its + data.obj.height();
			
			if ((its > ts && its < tn) || (itn > ts && itn < tn)) {
				data.obj.attr('src', data.url);
				data.obj = null;
			}
		});
	}
};

;(function($) {
	$.fn.scrollLoading = function(options) {
		var l = new web.ScrollLoading(options);
		l.addImgsAndShow(this);
	}
})(jQuery);